package com.bw.ivideo.appversion.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.ivideo.appversion.intent.VersionIntent
import com.bw.ivideo.appversion.model.entity.AppVersionEntity
import com.bw.ivideo.appversion.model.service.AppVersionService
import com.bw.ivideo.appversion.state.VersionState
import com.bw.lib_mvicore.model.BaseModel
import com.bw.lib_net.entity.ResponseEntity
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/28 11:42
 * @Description :
 */
class AppVersionViewModel: BaseModel<VersionIntent>() {

    private val service: AppVersionService by lazy { AppVersionService() }
    private val _state: MutableStateFlow<VersionState> = MutableStateFlow(VersionState.Init)
    val state: StateFlow<VersionState> = _state.asStateFlow()

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is VersionIntent.GetAppVersionIntent -> doGetAppVersion(it)
                }
            }
        }
    }

    private fun doGetAppVersion(it: VersionIntent.GetAppVersionIntent) {
        viewModelScope.launch {
            flow<ResponseEntity<AppVersionEntity>> {
                val responseEntity = service.versionConfigurationUpdate(it.map)
                emit(responseEntity)
            }.catch {e->
                _state.value = VersionState.Error(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if (it.code == 0){
                    _state.value = VersionState.Success(it.data)
                }else{
                    _state.value = VersionState.Error(it.msg)
                }
            }
        }
    }


}